package com.fwx.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.Verification;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: springsecurity04
 * @description:
 * @author: 范文轩
 * @create: 2024-07-30 09:59
 **/

public class JWTUtil01 {
    
    // 定义签名
    private static String name = "fwx";
    
    // 生成token
    public static String createToken(String username){
        
        //定义头信息
        Map<String,Object> head = new HashMap<>();
        head.put("alg","HS256");
        head.put("typ","JWT");
        
        // 定义发布日期
        Date date = new Date();
        
        // 定义过期时间
        // 获取当前时间
        Calendar instance = Calendar.getInstance();
        // 在当前时间的基础商添加7200秒
        instance.set(Calendar.SECOND,7200);
        // 获取添加7200秒之后的时间
        Date time = instance.getTime();

        // 创建token
        String token = JWT.create()
                // 设置头信息
                .withHeader(head)
                // 设置发布日期
                .withIssuedAt(date)
                // 设置过期时间
                .withExpiresAt(time)
                // 设置个人信息
                .withClaim("username", username)
                // 设置签名
                .sign(Algorithm.HMAC256(name));
        
        return token;
    }
    
    // 校验token
    public static boolean verify(String token){
        Verification require = JWT.require(Algorithm.HMAC256(name));
        try {
            require.build().verify(token);
            return true;
        } catch (Exception e) {
            System.out.println("token错误");
            return false;
        }
    }
    
    // 根据token获取自定义的信息
    public static Claim getInfo(String token,String key){
        /*JWTVerifier build = JWT.require(Algorithm.HMAC256(name)).build();
        Claim claim = build.verify(token).getClaim(key);
        return claim;*/
        return JWT.require(Algorithm.HMAC256(name)).build().verify(token).getClaim(key);
    }

    public static void main(String[] args) {
        // 测试creatToken方法
        // String token = createToken("萧炎");
        // System.out.println(token);
        
        // 测试verify方法
        // System.out.println(verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MjIzMDc2NzcsImV4cCI6MTcyMjMxNDgyMCwidXNlcm5hbWUiOiLokKfngo4ifQ.N4whSmASHCFpvcWbti08i6NOLwz37Y7eyaohtODG7ic"));
        
        // 测试getInfo方法
        String token = createToken("萧炎");
        System.out.println(getInfo(token, "username"));
    }
}
